package uabc.arduino.monitores;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;

import org.jfree.data.time.Millisecond;

import uabc.arduino.archivo.CsvManager;
import uabc.arduino.elementos.SerieConfiguration;

public class MonitorTCP extends Monitor {
	private int recivePort;
	private int sendPort;
	private String remoteIP;
	private boolean running;
	private ServerSocket serverSocket;
	private BufferedReader in;
	private Socket connectionSocket;

	public MonitorTCP(int recivePort, String remoteIP, int sendPort) {
		this.recivePort = recivePort;
		this.remoteIP = remoteIP;
		this.sendPort = sendPort;
		running = true;
	}

	public void run() {
		try {
			serverSocket = new ServerSocket(recivePort);
		} catch (IOException e1) {
			e1.printStackTrace();
		}
		while (running) {
			try {
				connectionSocket = serverSocket.accept();
				in = new BufferedReader(new InputStreamReader(
						connectionSocket.getInputStream()));
				String cadena = in.readLine();
				System.out.println(cadena);
				setChanged();
				notifyObservers(cadena);
				in.close();
				connectionSocket.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		try {
			serverSocket.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void ejecutarComando(final String comando) {
		Thread tr = new Thread() {
			public void run() {
				try {
					Socket clientSocket = new Socket(remoteIP, sendPort);
					DataOutputStream outToServer = new DataOutputStream(
							clientSocket.getOutputStream());
					BufferedReader inFromServer = new BufferedReader(
							new InputStreamReader(clientSocket.getInputStream()));
					outToServer.writeBytes(" "+comando + "\n");
					outToServer.flush();
					String msgFromServer = null;
					while ((msgFromServer = inFromServer.readLine()) != null) {
						if (!msgFromServer.trim().equals("")) {
							System.out.println(msgFromServer);
							setChanged();
							notifyObservers(msgFromServer);
						}
					}
					outToServer.close();
					clientSocket.close();
				} catch (UnknownHostException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		};
		tr.start();
	}

	public void terminate() {
		running = false;
	}

	@Override
	public boolean testConnection() {
		// TODO Auto-generated method stub
		return false;
	}

	public void delay(long miliSeconds) {
		try {
			Thread.sleep(miliSeconds);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
}
